﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.JScript;
using System.Reflection;

namespace SMS.Common.Runtime
{
    public class JscriptEngine
    {
        public object Eval(string script, object context)
        {
            Type _evaluatorType = null;
            string _jscriptSource = @"package JScript{
public class Eval{
    public function EvalExpression(context, exp){
        return function(){
                return eval(exp);
            }.call(context);
    }
}}";

            JScriptCodeProvider compiler = new JScriptCodeProvider();

            CompilerParameters parameters;
            parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;

            CompilerResults results;
            results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
            Assembly assembly = results.CompiledAssembly;
            _evaluatorType = assembly.GetType("JScript.Eval");
            object[] p = new object[] { context, script };
            object target = Activator.CreateInstance(_evaluatorType);
            object r = _evaluatorType.InvokeMember("EvalExpression", BindingFlags.InvokeMethod,
                        null, target, p);

            return r;
        }
    }
}
